package com.ebs.md.fxmonitor.marketmonitor.esper.log;

/**
 * Perforce Revision:
 *  $File: //depot/MarketData/fxmonitor/main/src/main/java/com/ebs/md/fxmonitor/marketmonitor/esper/log/EsperListenerLogger.java $
 *  $Revision: #2 $  $Change: 114341 $  $DateTime: 2012/08/29 16:38:26 $  $Author: Arik.Sher $
 */

import org.apache.log4j.Logger;

import com.ebs.commons.util.CollUtils;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPStatement;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.StatementAwareUpdateListener;


public class EsperListenerLogger
implements StatementAwareUpdateListener
{
    final protected Logger logger = Logger.getLogger(getClass());

	@Override
	public void update(EventBean[] newEvents, EventBean[] oldEvents, EPStatement epstatement, EPServiceProvider epserviceprovider) {
		final String stmtName = epstatement.getName();
		
		if ( logger.isInfoEnabled() ) {
			logger.info ( buildLog(stmtName + ": newEvents", newEvents));
		}
		if ( logger.isDebugEnabled() ) {
			logger.info ( buildLog(stmtName + ": oldEvents", oldEvents));
		}
	}

	protected static final String SEPERATOR = " ,|, ";
	
	protected String buildLog(String prefix, EventBean[] events) {
		StringBuffer sb = new StringBuffer(prefix);
		
		if ( !CollUtils.isEmpty(events) ) {
			sb.append(" (count=");
			sb.append(events.length);
			sb.append(") = ");
			
			boolean isFirst = true;
			sb.append("{");
			for ( EventBean curr : events ) {
				if ( !isFirst ) {
					sb.append(SEPERATOR);
				}
				sb.append(curr);
				
				isFirst = false;
			}
			sb.append("}");
		} else {
			sb.append("none");
		}
		return sb.toString();
	}
	
}
